import { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import Nabar from '../../conpoment/Nabar';
import img from './img/image.png'
import styles from './index.module.css';

// 预约项目接口
interface AppointmentItem {
  id: string;
  title: string;
  orderTime: string;
  status: 'pending' | 'booked' | 'cancelled' | 'completed';
  type: 'check' | 'test' | 'medicine';
  appointmentDetails?: {
    date: string;
    day: string;
    time: string;
    room: string;
    available: number;
    fullDate: string;
    hospital?: string;
    patient?: string;
  };
}

function Index() {
  const navigate = useNavigate();
  const location = useLocation();
  const [appointment, setAppointment] = useState<AppointmentItem | null>(null);
  const [isTestMode, setIsTestMode] = useState(false);

  useEffect(() => {
    // 从路由参数或状态中获取预约信息
    const appointmentData = location.state?.appointment;
    if (appointmentData) {
      setAppointment(appointmentData);
    } else {
      // 如果没有传递数据，返回上一页
      navigate(-1);
    }
  }, [location.state, navigate]);

  if (!appointment) {
    return (
      <div className={styles.container}>
        <Nabar title="预约详情" sticky={false} />
        <div className={styles.loading}>加载中...</div>
      </div>
    );
  }

  // 生成条形码数据
  const barcodeData = `20200101001598Z`;
  const appointmentNumber = `202001010653`;

  // 判断检查状态 - 根据预约状态直接判断
  const isCompleted = () => {
    if (!appointment) return false;
    
    // 根据预约状态判断
    if (appointment.status === 'completed') {
      return true;
    } else if (appointment.status === 'cancelled') {
      return false; // 已取消的不算完成
    } else if (appointment.status === 'booked') {
      // 如果是已预约状态，根据时间判断是否完成
      if (!appointment.appointmentDetails?.fullDate) return false;
      
      const appointmentTime = new Date(appointment.appointmentDetails.fullDate);
      const now = new Date();
      
      // 如果当前时间超过预约时间1小时，认为已完成检查
      const timeDiff = now.getTime() - appointmentTime.getTime();
      const hoursDiff = timeDiff / (1000 * 60 * 60);
      
      return hoursDiff > 1;
    }
    
    return false;
  };

  const checkStatus = isCompleted();
  const statusText = checkStatus ? '已检查' : '待检查';
  const statusIcon = checkStatus ? '✅' : '🕐';
  const statusDescription = checkStatus 
    ? '检查已完成，感谢您的配合' 
    : '您已完成预约。请按照预约时间及时到院签到';

  const handleMarkCompleted = () => {
    if (!appointment) return;
    
    // 更新预约状态为已完成
    const updatedAppointment = {
      ...appointment,
      status: 'completed' as const
    };
    
    // 更新本地存储中的预约数据
    const existingBooked = JSON.parse(localStorage.getItem('bookedAppointments') || '[]');
    const updatedBooked = existingBooked.map((item: AppointmentItem) => 
      item.id === appointment.id ? updatedAppointment : item
    );
    localStorage.setItem('bookedAppointments', JSON.stringify(updatedBooked));
    
    // 更新当前状态
    setAppointment(updatedAppointment);
    
    alert('已标记为检查完成');
  };

  return (
    <div className={styles.container}>
      {/* 顶部导航栏 */}
      <Nabar title="预约详情" sticky={false} />
      
      {/* 预约状态区域 */}
      <div className={styles.statusSection}>
        <div className={styles.statusInfo}>
          <div className={styles.statusIcon}>{statusIcon}</div>
          <div className={`${styles.statusText} ${checkStatus ? styles.completed : styles.pending}`}>
            {statusText}
          </div>
        </div>
        <div className={styles.statusDescription}>
          {statusDescription}
        </div>
      </div>

      {/* 条形码区域 */}
      <div className={styles.barcodeSection}>
        <div className={styles.barcodeContainer}>
        <img src={img} alt="" />
        </div>
        <div className={styles.barcodeNumber}>{barcodeData}</div>
        <div className={styles.barcodeDescription}>检查签到时可出示此码</div>
      </div>

      {/* 患者信息 */}
      <div className={styles.patientSection}>
        <div className={styles.sectionTitle}>患者信息</div>
        <div className={styles.infoGrid}>
          <div className={styles.infoItem}>
            <span className={styles.label}>预约医院</span>
            <span className={styles.value}>四川省保健院北苑</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>就诊患者</span>
            <span className={styles.value}>王小柯</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>登记号</span>
            <span className={styles.value}>{barcodeData}</span>
          </div>
        </div>
      </div>

      {/* 预约信息 */}
      <div className={styles.appointmentSection}>
        <div className={styles.sectionTitle}>预约信息</div>
        <div className={styles.infoGrid}>
          <div className={styles.infoItem}>
            <span className={styles.label}>预约项目</span>
            <span className={styles.value}>{appointment.title}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>检查诊室</span>
            <span className={styles.value}>{appointment.appointmentDetails?.room || 'CT诊室一'}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>检查地点</span>
            <span className={styles.value}>门诊二楼放射科</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>预约时间</span>
            <span className={styles.value}>{appointment.appointmentDetails?.fullDate || '2020-01-01 08:30-09:30'}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>预约单号</span>
            <span className={styles.value}>{appointmentNumber}</span>
          </div>
        </div>
      </div>

      {/* 操作按钮 - 只有待检查状态才显示 */}
      {!checkStatus && (
        <div className={styles.actionButtons}>
          <button 
            className={styles.completeButton}
            onClick={handleMarkCompleted}
          >
            标记检查完成
          </button>
        </div>
      )}

      {/* 测试按钮 - 用于切换状态 */}
      <div className={styles.testButtons}>
        <button 
          className={styles.testButton}
          onClick={() => setIsTestMode(!isTestMode)}
        >
          {isTestMode ? '退出测试模式' : '进入测试模式'}
        </button>
        {isTestMode && (
          <button 
            className={styles.testButton}
            onClick={() => {
              if (appointment) {
                setAppointment({
                  ...appointment,
                  status: appointment.status === 'completed' ? 'booked' : 'completed'
                });
              }
            }}
          >
            切换检查状态
          </button>
        )}
      </div>
    </div>
  );
}

export default Index;
